package com.cty.controller;

import com.cty.pojo.Customer;
import com.cty.service.CustomerService;
import com.cty.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping("/customer")
    @ResponseBody
    public ServerResult regist(Customer customer){
        System.out.println("controller customer :" + customer);
        ServerResult serverResult = customerService.regist(customer);

         return serverResult;
    }

    @PostMapping("/customer/login")
    public String login(Long cusTelno, String cusPwd, HttpServletRequest request,HttpSession session){
        System.out.println("controller customer login:" + cusTelno + ", cusPwd" +cusPwd);
        ServerResult serverResult = customerService.login(cusTelno,cusPwd);

        if(serverResult.getCode() ==200){
            System.out.println("controller login success ");
            Customer customer = (Customer)serverResult.getData();
            System.out.println("login success, and customer is :" + customer);
            session.setAttribute("loginCustomer",customer); // binding login customer to session
            return "redirect:/index.jsp";
        }else {
            System.out.println("controller login fail ");
            request.setAttribute("loginMsg","customer telno or password is error,please input again.");
            return "member/login";
        }

    }


    @GetMapping("/customer/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginCustomer");
        return "redirect:/index.jsp";
    }
}
